package com.site.wisdom_construction.controller.publicModule;

import com.site.wisdom_construction.util.imgUtil.AliyunOSSUtil;
import com.site.wisdom_construction.util.verification.NoToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/** @Author daiyifei @Date 2022/3/14 @Description */
@Api(tags = "阿里云oss图片接口")
@RestController
@RequestMapping("PictureUpload")
@CrossOrigin
public class PictureUploadController {

  @ApiOperation(value = "人员现场拍照图片", notes = "")
  @PostMapping("personPicture")
  @NoToken
  public String picture(@RequestParam("file") MultipartFile file) {
    String oldFileName = file.getOriginalFilename();
    int lastDotIndex = oldFileName.lastIndexOf(".");
    String extName = oldFileName.substring(lastDotIndex);
    String newName = UUID.randomUUID() + extName;
    File excelFile = new File("/root/personImg/" + newName);
    try {
      file.transferTo(excelFile);
      return newName;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "false";
  }

  @ApiOperation(value = "身份证正反面图片上传", notes = "")
  @PostMapping("/personCardImgUpload")
  @NoToken
  public String personCardImgUpload(MultipartFile file) {

    try {

      if (null != file) {
        String filename = file.getOriginalFilename();
        if (!"".equals(filename.trim())) {
          File newFile = new File(filename);
          FileOutputStream os = new FileOutputStream(newFile);
          os.write(file.getBytes());
          os.close();
          file.transferTo(newFile);
          String Host = "personCardImg";
          // 上传到OSS
          String uploadUrl = AliyunOSSUtil.upload(newFile, Host);
          // 删除上传时缓存在服务器上的文件
          newFile.delete();
          return uploadUrl;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return "upload";
  }
}
